package com.wuyan.web.base.helper.convert;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.AttributeConverter;
import java.util.Arrays;
import java.util.List;

/**
 * AttributeConverter: 此接口用于转化实体属性的
 * 将实体类中的List与数据库中的String互转
 */

@Slf4j
public class List2StringConvert implements AttributeConverter<List<?>, String> {
    private final static String SPLIT = "\\|";
    private final static String TAG = "|";

    @Override
    public String convertToDatabaseColumn(List value) {
        return getDatabaseColumn(value);
    }

    @Override
    public List<?> convertToEntityAttribute(String value) {
        return getEntityAttribute(value);
    }

    public static String getDatabaseColumn(List<?> value) {
        try {
            if (null == value || value.size() == 0) {
                return null;
            }

            return StringUtils.join(value, TAG);
        } catch (Exception e) {
            log.error("实体属性转换到表字段,{}", e.getMessage(), e);
        }
        return null;
    }

    public static List<String> getEntityAttribute(String value) {
        try {
            if (StringUtils.isEmpty(value)) {
                return null;
            }

            String[] steps = value.split(SPLIT);

            return Arrays.asList(steps);
        } catch (Exception e) {
            log.error("表字段转换到实体属性, {}", e.getMessage(), e);
        }

        return null;
    }

}
